package com.computergames.server.server.handler;

import com.computergames.server.message.CreateRoomRequestMessage;
import com.computergames.server.message.CreateRoomResponseMessage;
import com.computergames.server.message.ErrorResponseMessage;
import com.computergames.server.server.session.Room;
import com.computergames.server.server.session.RoomSessionFactory;
import com.computergames.server.server.session.RoomSessionService;
import com.computergames.server.server.session.SessionFactory;
import com.computergames.server.service.Interface.CheckAndUpdateClientState;
import com.computergames.server.util.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import com.computergames.server.domain.ClientState;
import io.netty.util.AttributeKey;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@ChannelHandler.Sharable
public class CreateRoomRequestMessageHandler extends SimpleChannelInboundHandler<CreateRoomRequestMessage> {
    private static final AttributeKey<String> USER_ROOM_KEY = AttributeKey.valueOf("USER_ROOM");
    private static final Map<String, Set<String>> roomName_members = new ConcurrentHashMap<>();
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, CreateRoomRequestMessage msg) throws Exception {
        CheckAndUpdateClientState checkAndUpdateClientState = SpringUtil.getBean(CheckAndUpdateClientState.class);
        if(checkAndUpdateClientState.checkState(channelHandlerContext, ClientState.STAGE_SELECTED)){
            String roomName = msg.getRoomName();
            String roomType = msg.getRoomType();
            List<String> members = msg.getMembers();
            Set<String> uniqueMembers = new LinkedHashSet<>(members);
            String stage = (String)channelHandlerContext.channel().attr(AttributeKey.valueOf("USER_STAGE")).get();
            RoomSessionService roomSessionService = RoomSessionFactory.getRoomSession();

            if(members.size() != uniqueMembers.size()){
                channelHandlerContext.writeAndFlush(new CreateRoomResponseMessage(false, "房间成员不能重复"));
                return;
            }

            for (String member : members) {
                Channel channel = null;
                channel = SessionFactory.getSession().getChannel(member);
                if(channel == null){
                    channelHandlerContext.writeAndFlush(new CreateRoomResponseMessage(false, member + "用户不在线或不存在"));
                    return;
                }
                if(stage != channel.attr(AttributeKey.valueOf("USER_STAGE")).get()){
                    channelHandlerContext.writeAndFlush(new CreateRoomResponseMessage(false, member + "用户不在当前比赛阶段"));
                    return;
                }
            }

            Room room = roomSessionService.createRoom(roomName, roomType, members);
            if(room == null){
                channelHandlerContext.writeAndFlush(new CreateRoomResponseMessage(false, roomName + "创建失败"));
                return;
            } else {
                //channel与房间名绑定
                channelHandlerContext.channel().attr(USER_ROOM_KEY).set(roomName);
                checkAndUpdateClientState.updateState(channelHandlerContext.channel(), ClientState.ROOM_CREATED);//更新状态
                roomName_members.put(roomName, uniqueMembers);
                channelHandlerContext.writeAndFlush(new CreateRoomResponseMessage(true, roomName + "创建成功"));
                String firstMember = members.getFirst(); // 获取第一个元素
                List<Channel> channels = roomSessionService.getMembersChannel(roomName);
                for (Channel channel : channels) {
                    // 确保此通道对应的用户不是房间创建者
                    if (!channel.attr(AttributeKey.valueOf("USER_IDENTIFIER")).get().equals(firstMember)) {
                        channel.writeAndFlush(new CreateRoomResponseMessage(true, "您已被拉入 " + roomName));
                        channel.attr(USER_ROOM_KEY).set(roomName);
                        checkAndUpdateClientState.updateState(channel, ClientState.ROOM_JOINED);//更新状态
                    }
                }
            }

            if(roomSessionService.isRoomFull(roomName)){
                List<Channel> channels = roomSessionService.getMembersChannel(roomName);
                for (Channel channel : channels) {
                    channel.writeAndFlush(new CreateRoomResponseMessage(true, roomName + "房间人数已满，请准备"));
                    checkAndUpdateClientState.updateState(channel, ClientState.GAME_READY);
                }
            }
        } else{
            channelHandlerContext.writeAndFlush(new ErrorResponseMessage("当前状态不能进行房间创建"));
        }
    }

    public static Map<String, Set<String>> getRoomName_members() {
        // 返回只读的Map
        return Collections.unmodifiableMap(roomName_members);
    }
}
